package com.ilop.sthome.utils.system;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import static android.content.Context.WIFI_SERVICE;

/**
 * @author skygge
 * @date 2020/8/7.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：便捷式热点操作管理
 */
public class WifiApManage {

    private static final String AP_CONNECTED = "0x2";
    private static final String AP_DEVICE_TYPE = "wlan0";
    private static final int WIFI_NONE_TYPE = 0;
    private static final int WIFI_WEP_TYPE = 1;
    private static final int WIFI_WPA_TYPE = 2;
    private static final int WIFI_PSK_TYPE = 3;

    private Context mContext;
    private static WifiApManage mWifiApManage;
    private WifiManager mWifiManager;
    private WifiConfiguration mWifiConfiguration;

    public static WifiApManage newInstance(Context context) {
        if (null == mWifiApManage) {
            synchronized (WifiApManage.class){
                mWifiApManage = new WifiApManage(context);
            }
        }
        return mWifiApManage;
    }

    public WifiApManage(Context context) {
        this.mContext = context;
        mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
    }

    /**
     * 关闭热点
     * 亲测可用 适配Android9.0
     */
    @TargetApi(Build.VERSION_CODES.N)
    public void stopHotPoint() {
        try {
            ConnectivityManager manager = mContext.getApplicationContext().getSystemService(ConnectivityManager.class);
            assert manager != null;
            Method method = manager.getClass().getDeclaredMethod("stopTethering", int.class);
            method.invoke(manager, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建热点
     *
     * @param ssid   热点名称
     * @param passwd 热点密码
     * @param type   热点类型
     */
    public void startWifiAp(String ssid, String passwd, int type) {
        Method method;
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
        try {
            WifiConfiguration netConfig = new WifiConfiguration();
            netConfig.SSID = ssid;
            netConfig.preSharedKey = passwd;
            netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

            switch (type) {
                case WIFI_NONE_TYPE:
                    netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    netConfig.preSharedKey = null;
                    break;
                case WIFI_WEP_TYPE:
                case WIFI_PSK_TYPE:
                case WIFI_WPA_TYPE:
                    netConfig.allowedKeyManagement.set(4);
                    break;
                default:
                    break;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Method configMethod = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
                configMethod.invoke(mWifiManager, netConfig);
            } else {
                method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
                method.invoke(mWifiManager, netConfig, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开启热点
     */
    public void openWifiAp() {
        Method method;
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }

        if (!isWifiApEnabled()) {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    mWifiConfiguration = getWifiApInfo();
                    Method configMethod = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
                    configMethod.invoke(mWifiManager, mWifiConfiguration);
                    method = mWifiManager.getClass().getMethod("startSoftAp", WifiConfiguration.class);
                    //返回热点打开状态
                    method.invoke(mWifiManager, mWifiConfiguration);
                } else {
                    method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
                    method.setAccessible(true);
                    WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);
                    Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
                    method2.invoke(mWifiManager, config, true);
                }
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭热点
     */
    @SuppressLint({"ObsoleteSdkInt", "SoonBlockedPrivateApi"})
    public void closeWifiAp() {
        Method method ;
        if (isWifiApEnabled()) {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    method = mWifiManager.getClass().getDeclaredMethod("stopSoftAp");
                    method.invoke(mWifiManager);
                } else {
                    method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
                    method.setAccessible(true);
                    WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);
                    Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
                    method2.invoke(mWifiManager, config, false);
                }
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取便捷式热点状态
     */
    public boolean isWifiApEnabled() {
        try {
           Method method = mWifiManager.getClass().getDeclaredMethod("getWifiApState");
            //调用getWifiApState() ，获取返回值
            int state = (int) method.invoke(mWifiManager);
            //通过放射获取 WIFI_AP的开启状态属性
            Field field = mWifiManager.getClass().getDeclaredField("WIFI_AP_STATE_ENABLED");
            //获取属性值
            int value = (int) field.get(mWifiManager);
            //判断是否开启
            return state == value;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return false;
    }

    public WifiConfiguration getWifiApInfo() {
        try {
            Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
            method.setAccessible(true);
            mWifiConfiguration = (WifiConfiguration) method.invoke(mWifiManager);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return mWifiConfiguration;
    }


    /**
     * 开热点手机获得其他连接手机IP的方法
     *
     * @return 其他手机IP 数组列表
     */
    public ArrayList<String> getConnectedIP() {
        ArrayList<String> connectedIp = new ArrayList<>();
        BufferedReader br = null;
        FileReader fileReader = null;
        boolean flags = true;
        try {
            String line;
            fileReader = new FileReader("/proc/net/arp");
            br = new BufferedReader(fileReader);

            mWifiManager.getDhcpInfo().toString();

            while ((line = br.readLine()) != null) {
                if (!flags) {
                    final String[] splitted = line.split(" + ");
                    if (splitted.length >= 6) {
                        if (splitted[2].equals(AP_CONNECTED) && splitted[5].equals(AP_DEVICE_TYPE)) {
                            connectedIp.add(splitted[0] + " " + splitted[3]);
                        }
                    }
                }
                flags = false;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fileReader) {
                    fileReader.close();
                }
                if (null != br) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return connectedIp;
    }

    public String getClientDeviceName() {
        BufferedReader br = null;
        FileReader fileReader = null;

        try {
            fileReader = new FileReader("/data/misc/dhcp/dnsmasq.leases");
            br = new BufferedReader(fileReader);
            String line = "";
            while ((line = br.readLine()) != null) {
                if (line.indexOf("") != 1) {
                    String[] fields = line.split(" ");
                    //校验数据是不是破损
                    if (fields.length > 4) {
                        //返回第4个栏位

                        return fields[3];
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fileReader) {
                    fileReader.close();
                }

                if (null != br) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

}

